<?php

namespace app\api\controller;

use app\api\model\ConfigPrice;
use app\api\model\Juhe;
use OSS\Core\OssException;
use OSS\OssClient;
use think\Db;
use app\api\model\Cluster;
use think\Request;
use app\api\model\ConfigSystem as Config;
use app\api\model\User;
use app\api\model\Timing as TimingModel;
use app\api\model\OrderCommon;
use app\api\model\Topup;

class Timingbak extends Common
{
    // 返还聊天金额 (1分钟)
    private function returnMoney()
    {
        $data = Db::name('privatechat')->where([
            'score' => ['gt', 0],
            'finish' => 0,
            'addtime' => ['elt', date('Y-m-d H:i:s', strtotime('-12 hour'))]
        ])->select();

        if ($data) {
            $tips = [];

            $ids = array_column((array)$data, 'touserid');

            $users = Db::name('user')->where(['id' => ['in', $ids]])->column('id, name, phone');

            $giftIds = [];
            foreach ($data as $item) {
                if ($item['type'] == 8) {
                    $datas = json_decode($item['data'], true);
                    $giftIds[] = $datas['id'];
                }
            }

            $gifts = [];
            if ($giftIds) {
                $gifts = Db::name('user')->where(['id' => ['in', $giftIds]])->column('id, name');
            }

            $desc = [];
            foreach ($data as $item) {
                Db::name('user')->where(['id' => $item['userid']])->setInc('volley', $item['money']);

                if (isset($users[$item['touserid']])) {
                    $name = $users[$item['touserid']]['name'];
                    $id = $users[$item['touserid']]['id'];
                } else {
                    $name = '账号已注销';
                    $id = '未知';
                }

                if ($item['type'] == 8) {
                    $datas = json_decode($item['data'], true);

                    if (isset($gifts[$datas['id']])) {
                        $giftName = $gifts[$datas['id']];
                    } else {
                        $giftName = '未知';
                    }

                    $msg = $name . '(' . $id . ')未领取礼物【' . $giftName . '】，过期返还金币';
                } else {
                    $msg = $name . '(' . $id . ')未回复消息，过期返还金币';
                }

                $desc[] = [
                    'user_id' => $item['userid'],
                    'content' => $msg,
                    'price' => $item['money'],
                    'types' => 1,
                    'time' => time()
                ];

                if (array_key_exists($item['userid'] . ',' . $item['touserid'], $tips)) {
                    $tips[$item['userid'] . ',' . $item['touserid']] += $item['money'];
                } else {
                    $tips[$item['userid'] . ',' . $item['touserid']] = $item['money'];
                }
            }

            Db::name('volley_desc')->insertAll($desc);

            $ids = array_column((array)$data, 'id');
            Db::name('privatechat')->where(['id' => ['in', $ids]])->setField('finish', 1);


            if ($tips) {
                $tipsMeta = [];
                foreach ($tips as $key => $item) {
                    $both = explode(',', $key);
                    $tipsMeta[] = [
                        "type" => -1,
                        "userid" => $both['touserid'],
                        "touserid" => $both['userid'],
                        "content" => '对方未及时回复消息，' . $item . '金币已经退还到您的账户',
                        'single' => 1,
                        'isRead' => 1,
                        'sound_tip' => 1,
                        'finish' => 1
                    ];

                    $tipsMeta[] = [
                        "type" => -1,
                        "userid" => $both['userid'],
                        "touserid" => $both['touserid'],
                        "content" => '您没有及时回复对方的消息，' . $item . '金币已被退回',
                        'single' => 1,
                        'isRead' => 1,
                        'sound_tip' => 1,
                        'finish' => 1
                    ];
                }
                Db::name('privatechat')->insertAll($tipsMeta);
            }
        }
    }

    // 群排行 (30分钟)
    private function clusterRanking()
    {
        $data = Db::name('cluster')->where(['types' => 1, 'status' => 1])->order('active desc')->select();

        $contain = [];
        foreach ($data as $key => $item) {
            $contain[] = ['id' => $item['id'], 'ranking' => $key + 1];
        }

        if ($contain) {
            (new Cluster)->saveAll($contain);
        }

        Db::name('cluster')->where(['types' => 1, 'status' => ['neq', 1]])->setField('ranking', 0);

    }

    // 留存率记录 (00:05)
    private function tongjiUser()
    {
        $date = date('Y-m-d', strtotime('-1 day'));

        $data = Db::name('tongji_user')->where(['date' => $date])->find();

        if (!$data) {
            $count = Db::name('user')->whereTime('register_datetime', 'yesterday')->count();

            Db::name('tongji_user')->insert(['new_user' => $count, 'date' => $date, 'create_time' => time()]);
        }

        $data = Db::name('tongji_user')->whereTime('create_time', '-30 days')->select();

        foreach ($data as $key => $item) {

            if ($item['new_user']) {
                $start = date('Y-m-d H:i:s', strtotime($item['date']));
                $end = date('Y-m-d H:i:s', (strtotime($item['date']) + 86399));

                $update = [];

                $contain = ['next_day' => 1, 'three_day' => 2, 'four_day' => 3, 'five_day' => 4, 'six_day' => 5, 'seven_day' => 6, 'fifteen_day' => 14, 'thirty_day' => 29];

                foreach ($contain as $m => $n) {
                    $$m = strtotime($item['date']) + 86400 * $n;

                    if ($$m < time()) {

                        $count = Db::name('user')->where(['register_datetime' => ['between', [$start, $end]], 'last_login_datetime' => ['gt', date('Y-m-d H:i:s', $$m)]])->count();

                        $update[$m . '_keep'] = $count / $item['new_user'];
                    }
                }

                Db::name('tongji_user')->where(['id' => $item['id']])->update($update);
            }
        }
    }

    // 代理团队留存率记录 (00:10)
    private function tongjiProxy()
    {
        $date = date('Y-m-d', strtotime('-1 day'));

        $data = Db::name('tongji_proxy')->where(['date' => $date])->find();

        if (!$data) {
            $users = Db::name('user')->whereTime('register_datetime', 'yesterday')->select();

            $time = time();
            $contain = [];
            foreach ($users as $key => $item) {
                if ($item['yqr']) {
                    $parent = Db::name('user')->where(['yqm' => $item['yqr']])->value('id');

                    if ($parent) {
                        if (isset($contain[$parent])) {
                            $contain[$parent]['new_user']++;
                        } else {
                            $contain[$parent] = ['user_id' => $parent, 'new_user' => 1, 'date' => $date, 'create_time' => $time];
                        }
                    }
                }
            }

            if ($contain) {
                Db::name('tongji_proxy')->insertAll($contain);
            }
        }

        $data = Db::name('tongji_proxy')->whereTime('create_time', '-30 days')->select();

        foreach ($data as $key => $item) {

            if ($item['new_user']) {
                $start = date('Y-m-d H:i:s', strtotime($item['date']));
                $end = date('Y-m-d H:i:s', (strtotime($item['date']) + 86399));

                $update = [];

                $contain = ['next_day' => 1, 'three_day' => 2, 'four_day' => 3, 'five_day' => 4, 'six_day' => 5, 'seven_day' => 6, 'fifteen_day' => 14, 'thirty_day' => 29];

                foreach ($contain as $m => $n) {
                    $$m = strtotime($item['date']) + 86400 * $n;

                    if ($$m < time()) {
                        $yqm = Db::name('user')->where(['id' => $item['user_id']])->value('yqm');

                        if ($yqm) {
                            $count = Db::name('user')->where(['yqr' => $yqm, 'register_datetime' => ['between', [$start, $end]], 'last_login_datetime' => ['gt', date('Y-m-d H:i:s', $$m)]])->count();

                            $update[$m . '_keep'] = $count / $item['new_user'];
                        }
                    }
                }

                Db::name('tongji_proxy')->where(['id' => $item['id']])->update($update);
            }
        }
    }

    // 清除打招呼记录(00:00)
    private function emptyGreet()
    {
        //$start = strtotime(date('Ymd')) - 86400 * 3;
        //Db::name('greet_records')->where(['create_time' => ['lt', $start]])->delete();

        Db::name('user')->where(['id' => ['gt', 0]])->update(['greet_count' => 0, 'greet_time' => time(), 'greet_receive_count' => 0, 'greet_receive_time' => time()]);
    }

    // 自动打招呼(2分钟) (废弃，转到tp3)
    public function greet(Request $request = null)
    {
        $config = Db::name('config_system')->where(['category' => ['in', ['greet', 'kefu']]])->column('title, content');

        $kefu = (int)strip_tags($config['id']);

        if ($config['greet_newest']) {
            $space = $config['greet_newest'] + 60 * $config['greet_space'];
            if ($space > time()) {
                exit;
            }
        }

        if ($config['greet_switch'] + 0) {
            Config::where(['title' => 'greet_newest'])->update(['content' => time()]);

            $now = date('H');

            if ($config['greet_start'] <= $now && $now < $config['greet_end']) {
                $url = $request->domain() . str_replace('/index.php', '', $request->baseFile()) . '/apis/home/privatechat/addtalk';

                // 女性向男性打招呼
                // 男性
                $males = Db::name('user')->where([
                    'id' => ['neq', $kefu],
                    'sex' => '男',
                    'is_online' => 1,
                    'banned_end_time' => ['lt', date('Y-m-d H:i:s')],
                    'proxy' => 0,
                    'greet_receive_count' => ['lt', $config['greet_male_receive_max']]])
                    ->order('tycoon desc, volley desc, noble_grade desc')->select();

                if ($males) {
                    $contents = Db::name('privatechat_zhaohu')->where(['types' => 2, 'is_hidden' => 0])->cache(86400)->column('content');

                    if ($contents) {
                        $males_ids = array_column($males, 'id');

                        $females = Db::name('user')->field('id, greet_count, greet_time')->where([
                            'id' => ['neq', $kefu],
                            'sex' => '女',
                            'banned_end_time' => ['lt', date('Y-m-d H:i:s')],
                            'is_identity_authentication' => 2,
                            'proxy' => 0,
                            'greet_count' => ['lt', $config['greet_female_max']]
                        ])->order('role asc, is_online desc, charm_value desc, shouyi desc, following desc, zan desc, proxy desc')->select();

                        if ($females) {
                            $url = $request->domain() . str_replace('/index.php', '', $request->baseFile()) . '/apis/home/privatechat/addtalk?timing=1&greet=1';

                            $start = strtotime(date('Ymd')) - 86400 * 3;
                            $greetRecords = Db::name('greet_records')->where(['user_id' => ['in', $males_ids], 'create_time' => ['gt', $start]])->select();

                            $greetContain = [];
                            foreach ($greetRecords as $key => $item) {
                                $greetContain[] = $item['user_id'] . '+' . $item['to_user'];
                            }

                            $insert = [];
                            $update_male = [];
                            $update_female = [];
                            $current_time = time();
                            foreach ($males as $key => $item) {
                                $push_count = 0;
                                foreach ($females as $m => $n) {
                                    if ($push_count < $config['greet_female_count']) {
                                        if ($n['greet_count'] < $config['greet_female_max']) {
                                            $merge = $item['id'] . '+' . $n['id'];
                                            if (!in_array($merge, $greetContain)) {
                                                $greetContain[] = $merge;
                                                $insert[] = ['user_id' => $item['id'], 'to_user' => $n['id'], 'create_time' => $current_time];

                                                $females[$m]['greet_count'] = $n['greet_count'] = $n['greet_count'] + 1;

                                                if (isset($update_female[$n['id']])) {
                                                    $update_female[$n['id']]['greet_count'] = $n['greet_count'];
                                                    $update_female[$n['id']]['greet_time'] = $current_time;
                                                } else {
                                                    $update_female[$n['id']] = ['id' => $n['id'], 'greet_count' => $n['greet_count'], 'greet_time' => $current_time];
                                                }

                                                if (isset($update_male[$item['id']])) {
                                                    $update_male[$item['id']]['greet_receive_count'] = $item['greet_receive_count'];
                                                    $update_male[$item['id']]['greet_receive_time'] = $current_time;
                                                } else {
                                                    $update_male[$item['id']] = ['id' => $item['id'], 'greet_receive_count' => $item['greet_receive_count'], 'greet_receive_time' => $current_time];
                                                }

                                                $push_count += 1;

                                                $rand = mt_rand(0, count($contents) - 1);

                                                $data = [
                                                    'userid' => $n['id'],
                                                    'touserid' => $item['id'],
                                                    'content' => $contents[$rand],
                                                    'timing' => 1,
                                                    'greet' => 1,
                                                ];

                                                sendcurl($url, json_encode($data, JSON_UNESCAPED_UNICODE));
                                            }
                                        }
                                    } else {
                                        break;
                                    }
                                }
                            }

                            if ($insert) {
                                Db::name('greet_records')->insertAll($insert);
                            }

                            if ($update_female) {
                                (new User)->saveAll($update_female);
                            }

                            if ($update_male) {
                                (new User)->saveAll($update_male);
                            }
                        }
                    }
                }


                // 男性向女性打招呼
                // 女性
                $females = Db::name('user')->where([
                    'id' => ['neq', $kefu],
                    'sex' => '女',
                    'is_online' => 1,
                    'role' => 0,
                    'banned_end_time' => ['lt', date('Y-m-d H:i:s')],
                    'is_identity_authentication' => 2,
                    'proxy' => 0,
                    'greet_receive_count' => ['lt', $config['greet_female_receive_max']]
                ])->order('score desc, following desc, zan desc, charm_value desc')->select();

                if ($females) {
                    $contents = Db::name('privatechat_zhaohu')->where(['types' => 1, 'is_hidden' => 0])->cache(86400)->column('content');

                    if ($contents) {
                        $females_ids = array_column($females, 'id');

                        $males = Db::name('user')->where([
                            'id' => ['neq', $kefu],
                            'sex' => '男',
                            'banned_end_time' => ['lt', date('Y-m-d H:i:s')],
                            'proxy' => 0,
                            'greet_count' => ['lt', $config['greet_male_max']]
                        ])->order('is_online desc, noble_grade desc, volley desc, tycoon desc')->select();

                        if ($males) {

                            $start = strtotime(date('Ymd')) - 86400 * 3;
                            $greetRecords = Db::name('greet_records')->where(['user_id' => ['in', $females_ids], 'create_time' => ['gt', $start]])->select();

                            $greetContain = [];
                            foreach ($greetRecords as $key => $item) {
                                $greetContain[] = $item['user_id'] . '+' . $item['to_user'];
                            }

                            $insert = [];
                            $update_male = [];
                            $update_female = [];
                            $current_time = time();
                            foreach ($females as $key => $item) {
                                $push_count = 0;
                                foreach ($males as $m => $n) {
                                    if ($push_count < $config['greet_male_count']) {
                                        if ($n['greet_count'] < $config['greet_male_max']) {
                                            $merge = $item['id'] . '+' . $n['id'];
                                            if (!in_array($merge, $greetContain)) {
                                                $greetContain[] = $merge;
                                                $insert[] = ['user_id' => $item['id'], 'to_user' => $n['id'], 'create_time' => $current_time];

                                                $males[$m]['greet_count'] = $n['greet_count'] = $n['greet_count'] + 1;

                                                if (isset($update_male[$n['id']])) {
                                                    $update_male[$n['id']]['greet_count'] = $n['greet_count'];
                                                    $update_male[$n['id']]['greet_time'] = $current_time;
                                                } else {
                                                    $update_male[$n['id']] = ['id' => $n['id'], 'greet_count' => $n['greet_count'], 'greet_time' => $current_time];
                                                }

                                                if (isset($update_female[$item['id']])) {
                                                    $update_female[$item['id']]['greet_count'] = $item['greet_count'];
                                                    $update_female[$item['id']]['greet_time'] = $current_time;
                                                } else {
                                                    $update_female[$item['id']] = ['id' => $item['id'], 'greet_count' => $item['greet_count'], 'greet_time' => $current_time];
                                                }

                                                $push_count += 1;

                                                $rand = mt_rand(0, count($contents) - 1);

                                                $data = [
                                                    'userid' => $n['id'],
                                                    'touserid' => $item['id'],
                                                    'content' => $contents[$rand],
                                                    'timing' => 1,
                                                    'greet' => 1,
                                                ];

                                                sendcurl($url, json_encode($data, JSON_UNESCAPED_UNICODE));
                                            }
                                        }
                                    } else {
                                        break;
                                    }
                                }
                            }

                            if ($insert) {
                                Db::name('greet_records')->insertAll($insert);
                            }

                            if ($update_male) {
                                (new User)->saveAll($update_male);
                            }

                            if ($update_female) {
                                (new User)->saveAll($update_female);
                            }
                        }
                    }
                }
            }
        }
    }

    // 处理贵族过期 (23:55)
    public function checkNoble()
    {
        Db::name('user')->where(['noble_time' => ['elt', time()]])->setField('noble_grade', 0);

        $userNoble = Db::name('user_noble')->field('user_id, grade')->where(['expire' => ['gt', time()]])->order('grade desc')->group('user_id')->select();

        if ($userNoble) {
            $ids = array_column($userNoble, 'user_id');

            $users = Db::name('user')->where(['id' => ['in', $ids], 'noble_time' => ['gt', time()]])->column('id, grade');

            $contain = [];

            foreach ($userNoble as $item) {
                if ($item['grade'] < $users[$item['user_id']]) {
                    $contain[] = ['id' => $item['user_id'], 'grade' => $item['grade']];
                }
            }

            if ($contain) {
                (new User)->saveAll($contain);
            }
        }

    }

    // 平台每日利润 (23:58)
    public function bill()
    {
        $expense = Db::name('platform_balance')->where(['types' => 1])->whereTime('create_time', 'd')->sum('money');
        $income = Db::name('platform_balance')->where(['types' => 2])->whereTime('create_time', 'd')->sum('money');

        $result = Db::name('platform_bill')->where(['date' => date('Y-m-d')])->find();

        if (!$result) {
            $profit = $income - $expense;

            Db::name('platform_bill')->insert(['income' => $income, 'expense' => $expense, 'profit' => $profit, 'date' => date('Y-m-d'), 'create_time' => time()]);
        }
    }

    // 删除冗余数据 (00:05)
    private function emptyData()
    {
        Db::name('privatechat')->where(['type' => ['in', ['-1', '-2']], 'addtime' => ['lt', date('Y-m-d H:i:s', strtotime('-7 day'))]])->delete();
        Db::name('clusterchat')->where(['type' => ['in', ['-1', '-2']], 'addtime' => ['lt', date('Y-m-d H:i:s', strtotime('-7 day'))]])->delete();

        Db::name('sys_message')->where(['create_time' => ['lt', date('Y-m-d H:i:s', strtotime('-7 day'))]])->delete();

        Db::name('see_record')->where(['addtime' => ['lt', date('Y-m-d H:i:s', strtotime('-2 day'))]])->delete();

        Db::name('records_mate')->where(['create_time' => ['lt', strtotime('-5 day')]])->delete();

        $contents = Db::name('privatechat_zhaohu')->column('content');

        Db::name('privatechat')->where(['content' => ['in', $contents], 'addtime' => ['lt', date('Y-m-d H:i:s', strtotime('-2 day'))]])->delete();
        //Db::name('privatechat')->where(['content' => ['in', $contents]])->delete();

        Db::name('privatechat')->where(['data' => '{"prefix":"丘比特"}', 'addtime' => ['lt', date('Y-m-d H:i:s', strtotime('-2 day'))]])->delete();

        Db::name('privatechat')->where(['content' => '❤ ← 丘比特 → 发现你俩今天很有缘，为你们牵线成功~', 'addtime' => ['lt', date('Y-m-d H:i:s', strtotime('-2 day'))]])->delete();

        $contain = ['❤ ← 丘比特 → 发现你俩今天很有缘，为你们牵线成功~', '❤ ← 丘比特 → 牵线成功，给对方发消息可领取红包奖励'];
        Db::name('privatechat')->where(['content' => ['in', $contain], 'addtime' => ['lt', date('Y-m-d H:i:s', strtotime('-2 day'))]])->delete();

        // 贵族聊天特权次数使用记录
        Db::name('grade_noble_use')->where(['id' => ['gt', 0]])->delete();

        $kefu = Db::name('config_system')->where(['title' => 'id'])->value('content');
        $kefu = intval($kefu);

        Db::name('privatechat')->where(['userid' => ['neq', $kefu], 'touserid' => ['neq', $kefu], 'addtime' => ['lt', date('Y-m-d H:i:s', strtotime('-10 day'))]])->delete();
    }

    // 删除冗余数据 (30分钟)
    private function emptyGreetRecords()
    {
        $sql = "delete from greet_records where (user_id,to_user)
                in
                (select user_id,to_user from (select user_id,to_user from greet_records where id in (select id from greet_records group by user_id,to_user having count(*) > 1)  order by id) t) and id not in (select id from (select max(id) id from greet_records group by user_id,to_user having count(*) > 1) s)";
        Db::query($sql);
    }

    // 未读消息 短信提醒 (3分钟)
    public function smsTip()
    {
        $config = Db::name('config_system')->where(['category' => ['in', ['greet', 'kefu']]])->column('title, content');

        $kefu = (int)strip_tags($config['id']);

        $where = [
            'type' => ['in', ['0', '1', '2', '3', '8']],
            'userid' => ['neq', $kefu],
            'touserid' => ['neq', $kefu],
            'content' => ['neq', '{"prefix":"丘比特"}'],
            'isRead' => 0,
            'sms_tip' => 0,
            'addtime' => ['gt', date('Y-m-d H:i:s', strtotime('-5 minute'))]
        ];

        $data = Db::name('privatechat')->where($where)->select();


        if ($data) {
            $ids = $uids = [];
            foreach ($data as $key => $item) {
                if (!in_array($item['touserid'], $uids)) {
                    $uids[] = $item['touserid'];
                }

                $ids[] = $item['id'];
            }

            if ($uids) {
                //$users = Db::name('user')->where(['id' => ['in', $uids], 'phone' => ['not in', [' ', 'null']], 'role' => 0, 'sms_tip' => 0])->column('phone');
                $users = Db::name('user')->where(['id' => ['in', $uids], 'phone' => ['not in', [' ', 'null']], 'role' => 0])->column('phone');

                if ($users) {
                    $juhe = new Juhe();

                    foreach ($users as $phone) {
                        $juhe->send($phone);
                    }

                    //Db::name('user')->where(['phone' => ['in', $users]])->setField('sms_tip', 1);
                }
            }

            if ($ids) {
                Db::name('privatechat')->where(['id' => ['in', $ids]])->setField('sms_tip', 1);
            }
        }
    }

    // 同步过来用户 (05:00)
    private function synchUser()
    {
        $data = Db::connect("database2")->name("user")->where(['phone' => ['not in', [' ', 'null']]])->whereTime('register_datetime', 'yesterday')->select();

        if ($data) {
            $configPrice = ConfigPrice::where(['id' => ['gt', 0]])->order('min_charm_grade asc')->group('types')->column('types, price');

            $contain = $avatars = $prices = [];

            $phones = array_column($data, 'phone');

            $phones = Db::name('user')->where(['phone' => ['in', $phones]])->column('phone');

            foreach ($data as $key => $item) {
                if (!in_array($item['phone'], $phones)) {
                    if (stripos($item['head_portrait'], 'http')) {
                        $head_100 = $head_portrait = $item['sex'] == '男' ? '/public/style/api/img/male/' . mt_rand(1,20) . '.jpg' : '/public/style/api/img/female/' . mt_rand(1,20) . '.jpg';
                    } else {
                        $head_100 = $item['head_100'];
                        $head_portrait = $item['head_portrait'];
                    }

                    $contain[] = [
                        'name' => $item['name'],
                        'sex' => $item['sex'],
                        'phone' => $item['phone'],
                        'password' => $item['password'],
                        'wxcount' => $item['wxcount'],
                        'city' => $item['city'],
                        'head_100' => $head_100,
                        'head_300' => $head_100,
                        'head_portrait' => $head_portrait,
                        'birthday' => $item['birthday'],
                        'through_membership' => $item['through_membership'],
                        'age' => $item['age'],
                        'stature' => $item['stature'],
                        'weight' => $item['weight'],
                        'constellation' => $item['constellation'],
                        'slogan' => $item['slogan'],
                        'occupation' => $item['occupation'],
                        'education_background' => $item['education_background'],
                        'monthly_salary' => $item['monthly_salary'],
                        'self_slogan' => $item['self_slogan'],
                        'school_of_graduation' => $item['school_of_graduation'],
                        'emotion' => $item['emotion'],
                        'live_status' => $item['live_status'],
                        'is_house_purchase' => $item['is_house_purchase'],
                        'is_car_purchase' => $item['is_car_purchase'],
                        'longitude' => $item['longitude'],
                        'latitude' => $item['latitude'],
                        'register_datetime' => $item['register_datetime'],
                        'last_login_datetime' => $item['last_login_datetime'],
                        'yqm' => $item['yqm'],
                        'role' => 1,
                        'remote' => 1,
                    ];

                    if (stripos($item['head_100'], '/disk') !== false) {
                        $avatars[] = ['head_100' => $item['head_100'], 'head_portrait' => $item['head_portrait']];
                    }
                }
            }

            $servername = getenv('DB2_SERVERNAME');

            $this->getAvatar($avatars, $servername);

            Db::name('user')->insertAll($contain);

            $phones = array_column($contain, 'phone');

            $uids = Db::name('user')->where(['phone' => ['in', $phones]])->column('id');

            foreach ($uids as $item) {
                $prices[] = [
                    'user_id' => $item,
                    'chat_price' => $configPrice[1],
                    'voice_price' => $configPrice[2],
                    'video_price' => $configPrice[3]
                ];
            }

            Db::name('config_personal')->insertAll($prices);
        }
    }

    // 同步过来用户 (05:00)
    private function synchUser2()
    {
        $data = Db::connect("database3")->name("user")->where(['phone' => ['not in', [' ', 'null']]])->whereTime('register_datetime', 'yesterday')->select();

        if ($data) {
            $configPrice = ConfigPrice::where(['id' => ['gt', 0]])->order('min_charm_grade asc')->group('types')->column('types, price');

            $contain = $avatars = $prices = [];

            $phones = array_column($data, 'phone');

            $phones = Db::name('user')->where(['phone' => ['in', $phones]])->column('phone');

            foreach ($data as $key => $item) {
                if (!in_array($item['phone'], $phones)) {
                    if (stripos($item['head_portrait'], 'http') !== false) {
                        $head_100 = $head_portrait = $item['sex'] == '男' ? '/public/style/api/img/male/' . mt_rand(1,20) . '.jpg' : '/public/style/api/img/female/' . mt_rand(1,20) . '.jpg';
                    } else {
                        $head_100 = $item['head_100'];
                        $head_portrait = $item['head_portrait'];
                    }

                    $contain[] = [
                        'name' => $item['name'],
                        'sex' => $item['sex'],
                        'phone' => $item['phone'],
                        'password' => $item['password'],
                        'wxcount' => $item['wxcount'],
                        'city' => $item['city'],
                        'head_100' => $head_100,
                        'head_300' => $head_100,
                        'head_portrait' => $head_portrait,
                        'birthday' => $item['birthday'],
                        'through_membership' => $item['through_membership'],
                        'age' => $item['age'],
                        'stature' => $item['stature'],
                        'weight' => $item['weight'],
                        'constellation' => $item['constellation'],
                        'slogan' => $item['slogan'],
                        'occupation' => $item['occupation'],
                        'education_background' => $item['education_background'],
                        'monthly_salary' => $item['monthly_salary'],
                        'self_slogan' => $item['self_slogan'],
                        'school_of_graduation' => $item['school_of_graduation'],
                        'emotion' => $item['emotion'],
                        'is_house_purchase' => $item['is_house_purchase'],
                        'is_car_purchase' => $item['is_car_purchase'],
                        'longitude' => $item['longitude'],
                        'latitude' => $item['latitude'],
                        'register_datetime' => $item['register_datetime'],
                        'last_login_datetime' => $item['last_login_datetime'],
                        'yqm' => $item['yqm'],
                        'role' => 1,
                        'remote' => 1,
                    ];

                    if (stripos($item['head_100'], '/disk') !== false) {
                        $avatars[] = ['head_100' => $item['head_100'], 'head_portrait' => $item['head_portrait']];
                    }
                }
            }

            $servername = getenv('DB3_SERVERNAME');

            $this->getAvatar($avatars, $servername);

            Db::name('user')->insertAll($contain);

            $phones = array_column($contain, 'phone');

            $uids = Db::name('user')->where(['phone' => ['in', $phones]])->column('id, sex');

            foreach ($uids as $key => $item) {
                $prices[] = [
                    'user_id' => $key,
                    'chat_price' => $item == '女' ? $configPrice[1] : 0,
                    'voice_price' => $item == '女' ? $configPrice[2] : 0,
                    'video_price' => $item == '女' ? $configPrice[3] : 0
                ];
            }

            Db::name('config_personal')->insertAll($prices);
        }
    }
    
    // 同步过来用户 (05:00)
    private function synchUser3()
    {
        $data = Db::connect("database4")->name("user")->where(['phone' => ['not in', [' ', 'null']]])->whereTime('register_datetime', 'yesterday')->select();
        
        if ($data) {
            $configPrice = ConfigPrice::where(['id' => ['gt', 0]])->order('min_charm_grade asc')->group('types')->column('types, price');
            
            $contain = $avatars = $prices = [];
            
            $phones = array_column($data, 'phone');
            
            $phones = Db::name('user')->where(['phone' => ['in', $phones]])->column('phone');
            
            foreach ($data as $key => $item) {
                if (!in_array($item['phone'], $phones)) {
                    if (stripos($item['head_portrait'], 'http') !== false) {
                        $head_100 = $head_portrait = $item['sex'] == '男' ? '/public/style/api/img/male/' . mt_rand(1,20) . '.jpg' : '/public/style/api/img/female/' . mt_rand(1,20) . '.jpg';
                    } else {
                        $head_100 = $item['head_100'];
                        $head_portrait = $item['head_portrait'];
                    }

                    $contain[] = [
                        'name' => $item['name'],
                        'sex' => $item['sex'],
                        'phone' => $item['phone'],
                        'password' => $item['password'],
                        'wxcount' => $item['wxcount'],
                        'city' => $item['city'],
                        'head_100' => $head_100,
                        'head_300' => $head_100,
                        'head_portrait' => $head_portrait,
                        'birthday' => $item['birthday'],
                        'through_membership' => $item['through_membership'],
                        'age' => $item['age'],
                        'stature' => $item['stature'],
                        'weight' => $item['weight'],
                        'constellation' => $item['constellation'],
                        'slogan' => $item['slogan'],
                        'occupation' => $item['occupation'],
                        'education_background' => $item['education_background'],
                        'monthly_salary' => $item['monthly_salary'],
                        'self_slogan' => $item['self_slogan'],
                        'school_of_graduation' => $item['school_of_graduation'],
                        'emotion' => $item['emotion'],
                        'is_house_purchase' => $item['is_house_purchase'],
                        'is_car_purchase' => $item['is_car_purchase'],
                        'longitude' => $item['longitude'],
                        'latitude' => $item['latitude'],
                        'register_datetime' => $item['register_datetime'],
                        'last_login_datetime' => $item['last_login_datetime'],
                        'yqm' => $item['yqm'],
                        'role' => 1,
                        'remote' => 1,
                    ];
                    
                    if (stripos($item['head_100'], '/disk') !== false) {
                        $avatars[] = ['head_100' => $item['head_100'], 'head_portrait' => $item['head_portrait']];
                    }
                }
            }
            
            $servername = getenv('DB4_SERVERNAME');
            
            $this->getAvatar($avatars, $servername);
            
            Db::name('user')->insertAll($contain);
            
            $phones = array_column($contain, 'phone');
            
            $uids = Db::name('user')->where(['phone' => ['in', $phones]])->column('id, sex');
            
            foreach ($uids as $key => $item) {
                $prices[] = [
                    'user_id' => $key,
                    'chat_price' => $item == '女' ? $configPrice[1] : 0,
                    'voice_price' => $item == '女' ? $configPrice[2] : 0,
                    'video_price' => $item == '女' ? $configPrice[3] : 0
                ];
            }
            
            Db::name('config_personal')->insertAll($prices);
        }
    }

    private function getAvatar($files, $servername)
    {
        $oss = getenv('APP_OSS');

        $accessKeyId = getenv('OSS_KEYID');
        $accessKeySecret = getenv('OSS_KEYSECRET');
        $endpoint = getenv('OSS_ENDPOINT');
        $bucket = getenv('OSS_BUCKET');

        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

        foreach ($files as $key => $item) {
            $contain = [$item['head_100'], $item['head_portrait']];

            foreach ($contain as $m => $n) {
                if (stripos($n, 'http') !== false) {
                    $url = $n;

                    $directory = 'disk/uploads/images/' . date('Ymd', strtotime('-1 day'));

                    $name = mt_rand(100000, 999999) . ',png';

                    $n = $directory . '/' . $name;
                } else {
                    $url = 'http://' . $servername . $n;

                    $n = ltrim($n, '/');

                    $count = strripos($n, '/');

                    $directory = substr($n, 0, $count);
                    $name = substr($n, $count);
                }

                if (!is_dir($directory)) {
                    mkdir($directory, 0777, true);
                }

                mkFile($url, $n);

                if ($oss) {
                    $fileName = $directory . $name;

                    $localFile = str_replace('/index.php', '', $_SERVER['SCRIPT_FILENAME']) . '/' . $n;

                    try {
                        $ossClient->uploadFile($bucket, $fileName, $localFile);
                    } catch (OssException $e) {
                        return json(['code' => 400, 'msg' => $e->getMessage()]);
                    }

                    unlink($localFile);
                }
            }
        }
    }

    public function hours()
    {
        $this->checkOrder();
        $this->returnMoney();
        $this->clusterRanking();
        $this->emptyGreetRecords();
    }

    public function days()
    {
        $this->tongjiUser();
        $this->tongjiProxy();
        $this->emptyGreet();
        sleep(10);
        $this->emptyData();

        sleep(10);
        $this->synchUser();

        sleep(10);
        $this->synchUser2();
    
        sleep(10);
        $this->synchUser3();
    }

    public function yesterday()
    {
        $this->checkNoble();
        $this->bill();
    }
    
    public function halfAnHour()
    {
        $this->moneyTip();
    }
    
    private function moneyTip()
    {
        $config = Db::name('config_system')->where(['category' => 'kefu'])->column('title, content');
        
        $kefu = intval($config['id']);

        Db::name('user')->where(['id' => ['neq', $kefu], 'volley' => ['elt', 5000], 'balance_tip' => 1])->setField('balance_tip', 0);
        
        $where = [
            'id' => ['neq', $kefu],
            'volley' => ['gt', 5000],
            'balance_tip' => 0
        ];

        Db::name('user')->where($where)->setField('balance_tip', 1);

        $data = Db::name('user')->where($where)->column('phone');
        
        if ($data) {
            $juhe = new Juhe();
            $juhe->send(TimingModel::mobile());
        }
    }
    
    private function checkOrder()
    {
        $expire_time = time() - 1800;

        Topup::where(['state' => 0, 'addtime' => ['lt', date('Y-m-d H:i:s', $expire_time)]])->setField('state', 2);
        OrderCommon::where(['status' => 0, 'create_time' => ['lt', $expire_time]])->setField('status', -1);
    }
}
